<template>

</template>

<script>
  import { fromEventPattern } from 'rxjs';
  //自定义事件类
  class EventEmitter {
    constructor () {
      this.handlers = {}
    }
    on (eventName, handler) {
      if (!this.handlers[eventName]) {
        this.handlers[eventName] = []
      }
      if(typeof handler === 'function') {
        console.log('handler...is ', handler)
        this.handlers[eventName].push(handler)
      } else {
        throw new Error('handler 不是函数！！！')
      }
    }
    off (eventName, handler) {
      this.handlers[eventName].splice(this.handlers[eventName].indexOf(handler), 1)
    }
    emit (eventName, ...args) {
      this.handlers[eventName].forEach(handler => {
        handler(...args)
      })
    }
  }


  export default {
    name: "base-03",
    mounted(){
      const event = new EventEmitter()
      const subscription = fromEventPattern(
        event.on.bind(event, 'say'), ///奇怪的用法
        event.off.bind(event, 'say') ///奇怪的用法
        //event.on('say'),
        //event.off('say')
      ).subscribe(x => console.log(x))

      let timer = (() => {
        let number = 1
        return setInterval(() => {
          console.log('(interval',number,')')
          if (number === 5) {
            clearInterval(timer)
            console.log('最后, clearInterval.')
            timer = null
          }
          console.log('emitting ...')
          event.emit('say', number++)
        }, 1000)
      })()

      setTimeout(() => {
        console.log('准备取消订阅')
        subscription.unsubscribe()
        console.log('已取消')
      }, 3000)
    }
  }
</script>

<style scoped>

</style>
